const router = require('express').Router()
const validateToken = require('../../../../common/validateToken')
const status_code = require('../../../../common/status_code')
const db = require('../../../../db/async-db')
const { to } = require('await-to-js')
const { v4: uuidv4 } = require('uuid')
const Bee = require('../../../../common/bee/bee')
const baseUrl = require('../../../../common/baseUrl')

router.post('/avatar/upload', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { uid } = req.body
  let avatar = req.files.avatar
  if (!Bee.StringUtils.isNotBlank(uid) || !Bee.StringUtils.isNotBlank(avatar))
    return handleError(10003, '参数错误')

  const contents = `static/avatar/` // 文件存储路径
  // 单文件上传
  avatar.name = uuidv4() + '-' + avatar.name // 修改文件名称 避免重复

  avatar.mv(`${contents}${avatar.name}`, async (err) => {
    if (err) return res.status(500).json(err)
    const [updateAvatarError, updateAvatarSuccess] = await to(
      db.query('UPDATE userinfo SET avatar_url=? WHERE id=?', [
        baseUrl + '/' + contents + avatar.name,
        uid,
      ])
    )
    if (updateAvatarError || !updateAvatarSuccess)
      return handleError(-1, updateAvatarError)

    if (updateAvatarSuccess.affectedRows === 0) {
      return handleError(-1, '系统错误')
    }

    resp.json({
      code: 0,
      msg: status_code[0],
      data: {
        avatar: baseUrl + '/' + contents + avatar.name,
      },
    })
  })
})

module.exports = router
